<?php
	/* query.php
	*   by Allen Wu (103-790-579)
	*   CS 143, Spring 2012
	*   4/21/2012
	********************************************/

	$output = '';
	$query  = '';

	if (isset($_GET['query']) && trim($_GET['query']) !== '') {

		$db_connection = @mysql_connect('localhost', 'cs143', '');

		if (!$db_connection) {
			echo 'Connection failed.';
			exit(1);
		}

		else {
			mysql_select_db('CS143', $db_connection);

			$query = $_GET['query'];

			$result = @mysql_query($query, $db_connection);

			if ($result) {
				$printHeader = true;
				$output      = '<table>';

				// print each row
				while($row = mysql_fetch_assoc($result)) {
					// print table header
					if ($printHeader) {
						$output .= '<thead><tr>';
						foreach ($row as $key=>$cell) {
							$output .= "<th>{$key}</th>";
						}
						$output .= '</tr></thead><tbody>';
						$printHeader = false;
					}

					// print body cells
					$output .= '<tr>';
					foreach ($row as $cell) {
						$cell = empty($cell) ? 'N/A' : $cell;
						$output .= "<td>{$cell}</td>";
					}
					$output .= '</tr>';
				}
				$output .= '</tbody></table>';
			}
			else {$output = mysql_error($db_connection);}

			mysql_close($db_connection);
		}

	}

?>
<!DOCTYPE html>
<html>
	<head>
		<title>CS 143 Project 1B</title>
		<style type="text/css">
			table {
				border-collapse: collapse;
			}
			th {
				font-weight: bold;
			}
			th, td {
				border: 1px solid #000;
				padding: 4px;
			}
			textarea {
				width: 600px;
				height: 200px;
			}
		</style>
	</head>
	<body>
		<h1>CS 143 Project 1B - SQL Query</h1>
		<h2>by Allen Wu, 103-790-579</h2>
		<form method="GET">
			<textarea name="query"><?php echo $query; ?></textarea><br />
			<input type="submit" value="Calculate" />
		</form>
		<div id="result">
			<?php echo $output; ?>

		</div>
	</body>
</html>